package com.area42games.grammar.trees;

import java.util.HashMap;
import java.util.Stack;

import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CharStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;

import com.area42games.grammar.DiceLexer;
import com.area42games.grammar.DiceParser;
import com.area42games.grammar.DiceTreeAdaptor;
import com.google.wave.api.Blip;
import com.google.wave.api.Wavelet;

public class EvalContext 
{
	private Wavelet wavelet;
	private String username;
	private HashMap<String,String> memory = new HashMap<String,String>();
	private Stack<Integer> choice = new Stack<Integer>();

	public EvalContext(Wavelet wavelet, String user) 
	{
		this.wavelet = wavelet;
		this.username = user;
	}

	public void push(int value)
	{
		choice.push(value);
	}

	public int pop()
	{
		return choice.pop();
	}

	public int peek()
	{
		return choice.peek();
	}

	public void setLocal(String var, String expression)
	{
		this.memory.put(var,expression);		
	}
	
	public void set(String var, String expression) 
	{
		if(var.indexOf("!") > -1)
		{
			var = var.replace("!", username+".");
		}

		if(wavelet != null)
		{
			// This check is to allow for setting the Debug flag or other control statements.
			if(!var.startsWith("Area42Dice."))
			{
				var = "Area42Dice.set."+var;
			}
			this.wavelet.setDataDocument(var, expression);
		}

		this.memory.put(var,expression);
	}

	public String get(String var) throws InvalidReferenceException
	{
		if(var.indexOf("!") > -1)
		{
			var = var.replace("!", username+".");
		}
		
		if(this.memory.get(var) != null)
		{
			return this.memory.get(var);
		}

		if(this.wavelet != null)
		{
			return this.wavelet.getDataDocument("Area42Dice.set."+var);
		}
		
		throw new InvalidReferenceException(var);
	}

}
